<?php
/**
 * Shared User List
 * 
 * Display the list of user that the mailbox is shared with
 * 
 * 
 */

use Fox\Behaviors;
use Fox\Html\Button;
use Fox\Generator;
use Fox\Grid;

$xview = Xview::instance();
$inlineid = $xview->val('inlineid');
$codes = $xview->val('codes');
$reload = $xview->val('reload',false);
$grid = new Grid('gTarget',Generator::url('messages','mailbox','shared_users',array('inlineid' => $inlineid)));
$grid->fieldcat(array('first_name','last_name','email','idele'));
$grid->fieldcat()->switchToObjectMode();
$grid->fieldcat()->setGenerators(array(
	'first_name' => Generator::useFunction(function($data) {
		return $data->user()->firstName();
	}),
	'last_name' => Generator::useFunction(function($data) {
		return $data->user()->lastName();
	}),
	'email' => Generator::useFunction(function($data) {
		return $data->user()->email;
	}),
	'idele' => Generator::useValue('?')
));
$grid->fieldcat()->field('idele')
			->renderer()
			->behaviors(Behaviors::action(
				Generator::url('messages','mailbox','shared_remove',array('inlineid' => Generator::call('getInLineId'))),
				false,
				null,
				null,
				false,
				'POST',
				null,
				'tr',
				'udf',
				true
				
			));
$grid->footer()->add(new Button('add'))
		->behaviors(Behaviors::action(
			Generator::url('messages','mailbox','shared_add_users',array('inlineid' => $inlineid)),
			true
		));
		
try {
	$excludedValues = array();
	$mailbox = Fox\Dao::load(\Orx\User\MailBox::className(), $inlineid);
	foreach($mailbox->sharedUsers() as $sharedUser)  {
		$excludedValues[$sharedUser->shared_id] = $sharedUser;
	}
} catch(Fox\Object\Exception\NotExist $e) {
	$xview->systemError();
	exit;
}		
if(is_array($codes)) {
	foreach($codes as $code) {
		if(isset($excludedValues[$code])) {
			continue;
		}
		try {
			$sharingItem = new \Orx\User\Shared\Mailbox\Item();
			$sharingItem->setFields(array(
				'idusr' => $mailbox->idusr,
				'boxid' => $mailbox->boxid,
				'shared_id' => $code,
				'shared_reference' => $sharingItem::USER_REFERENCE
			));
			$sharingItem->create();
			$excludedValues[$sharingItem->shared_id] = $sharingItem;
		} catch (Fox\Object\Exception\Save $e) {
			Fox\Message::Error($e);
		}
	}
}
$grid->initialize($excludedValues);
// Populate the box
if($reload) {
	$html = $xview->messages(true);
	$html .= $grid->display();
	return $html;
} else {
	return $grid;
}
